package com.example.Servlet;

import com.example.Service.CommentService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import com.example.pojo.Comment;
import java.util.List;

@WebServlet(name = "GetCommentsByNews", value = "/GetCommentsByNews")
public class GetCommentsByNews extends HttpServlet {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String newsIdStr = request.getParameter("newsId");
        Map<String, Object> map = new HashMap<>();

        try {
            if (newsIdStr == null || newsIdStr.trim().isEmpty()) {
                map.put("code", 400);
                map.put("msg", "新闻ID不能为空");
                response.getWriter().append(new Gson().toJson(map));
                return;
            }
            int newsId = Integer.parseInt(newsIdStr);
            CommentService commentService = new CommentService();

            // 获取该新闻的所有评论（这里需要修改CommentDao添加按新闻ID查询的方法）
            List<Comment> comments = commentService.getCommentsByNewsId(newsId);

            map.put("code", 200);
            map.put("msg", "获取成功");
            map.put("data", comments);

        } catch (Exception e) {
            map.put("code", 500);
            map.put("msg", "服务器错误");
            e.printStackTrace();
        }

        response.getWriter().append(new Gson().toJson(map));
    }

            // Hello


    public void destroy() {
    }
}